<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="box">
      <div id="preload1"></div>
      <div id="preload2"></div>
      <div id="preload3"></div>
      <div id="preload4"></div>
    </div>
  </body>
  <script>
    // 预加载图片
    function preloader() {
      if (document.images) {
        // 实例化图片对象
        var img1 = new Image();
        var img2 = new Image();
        var img3 = new Image();
        var img4 = new Image();
        // 为图片对象添加属性
        img1.src = "./images/001.jpg";
        img2.src = "./images/002.jpg";
        img3.src = "./images/003.jpg";
        img4.src = "./images/004.jpg";
        // 或
        // var img1 = new Image().src = "./images/001.jpg";
        // var img2 = new Image().src = "./images/002.jpg";
        // var img3 = new Image().src = "./images/003.jpg";
        // var img4 = new Image().src = "./images/004.jpg";
      }
    }
    // 监听页面是否加载完成，只有加载完成后，才执行预加载
    function addLoadEvent(fn) {
      var load = window.onload;
      // 判断DOM是否加载完毕 加载完成后会获得回调函数
      if (typeof window.onload == "function") {
        // 页面加载完成，执行预加载
        window.onload = fn;
      } else {
        window.onload = function () {
          if (load) {
            load();
          }
          fn();
        };
      }
    }

    addLoadEvent(preloader);
  </script>
</html>
